package com.laibo.core.test;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.xml.parsers.SAXParser;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

class Excel {
    private HSSFWorkbook workBook;
    private HSSFSheet sheet;
    private int rowNum;
    private String xlsPath;
    private List<Map<String,Object>> rowList;
    private Map<String,String> fieldMap;

    Excel(Map<String,String> fieldMap,String xlsPath) {
        this.workBook = new HSSFWorkbook();
        this.sheet = this.workBook.createSheet("sheet1");
        this.rowNum = 0;
        this.xlsPath = xlsPath;
        this.fieldMap = fieldMap;
        this.addFirstRowToSheet();
        this.rowList = new LinkedList<>();
    }

    private void addRowToSheet(Map<String, Object> map) {
        HSSFRow row = sheet.createRow(this.rowNum++);
        int i = 0;
        for(Map.Entry<String,Object> entry: map.entrySet()){
            if(fieldMap.containsKey(entry.getKey())){
                String valueType = fieldMap.get(entry.getKey());
                if(valueType.equals("string")){
                    row.createCell(i).setCellValue(entry.getValue().toString());
                } else if (valueType.equals("int")){
                    Number num = (Number)entry.getValue();
                    row.createCell(i).setCellValue(num.intValue());
                } else if (valueType.equals("float")){
                    row.createCell(i).setCellValue(new DecimalFormat("#.00").format(entry.getValue()));
                }
                i++;
            }
        }
    }
    private void addFirstRowToSheet() {
        HSSFRow row = sheet.createRow(this.rowNum++);
        int i = 0;
        for(Map.Entry<String,String> entry: this.fieldMap.entrySet()){
            row.createCell(i).setCellValue(entry.getKey());
            i++;
        }
    }

    void compareTime(String controlGroupLogPath, String experimentalGroupLogPath, String field) throws IOException {
        int elasticTimeAverageControlGroup = readTimeFromLog(controlGroupLogPath,field);
        int elasticTimeAverageExperimentalGroup = readTimeFromLog(experimentalGroupLogPath,field);
        String result =
                field + "，\n" +
                        "对照组为 " + elasticTimeAverageControlGroup + " ms\n" +
                        "实验组为 " + elasticTimeAverageExperimentalGroup + " ms\n" +
                        "变化了" + Math.round((float)Math.abs(elasticTimeAverageControlGroup - elasticTimeAverageExperimentalGroup) * 100 / elasticTimeAverageControlGroup) + '%'
                ;
        System.out.println(result);
    }

    void compareSimilarity(String controlGroupExcelPath, String experimentalGroupExcelPath, int indexOfSimilarity) throws IOException {
        Map<String,Integer> similarityMapControlGroup = readExcelToMap(controlGroupExcelPath,indexOfSimilarity);
        Map<String,Integer> similarityMapExperimentalGroup = readExcelToMap(experimentalGroupExcelPath,indexOfSimilarity);

        int[] similarityControlHigherNum = {0};
        int[] similarityControlHigherTotal = {0};
        int[] similarityExperimentalHigherNum = {0};
        int[] similarityExperimentalHigherTotal = {0};
        similarityMapExperimentalGroup.forEach((docId,similarityExperimental)->{
            int similarityControl = similarityMapControlGroup.get(docId);
            int difference = similarityControl - similarityExperimental;
            if(difference > 0){
                similarityControlHigherNum[0] ++;
                similarityControlHigherTotal[0] += difference;
            } else if(difference < 0){
                similarityExperimentalHigherNum[0] ++;
                similarityExperimentalHigherTotal[0] += -difference;
            }
        });
        int similaritySameNum = similarityMapControlGroup.size() - similarityControlHigherNum[0] - similarityExperimentalHigherNum[0];
        int totalNum = similarityMapControlGroup.size();
        String result = totalNum + "篇中,\n" +
                "对照组相似率更高的有" + similarityControlHigherNum[0] + "个，占比" +
                Math.round((float) similarityControlHigherNum[0] * 100/ totalNum) + "%，平均每篇高" +
                Math.round((float) similarityControlHigherTotal[0] / similarityControlHigherNum[0]) + "%\n" +
                "实验组相似率更高的有" + similarityExperimentalHigherNum[0] + "个，占比" +
                Math.round((float) similarityExperimentalHigherNum[0] *100 / totalNum) + "%，平均每篇高" +
                Math.round((float) similarityExperimentalHigherTotal[0] / similarityExperimentalHigherNum[0]) + "%\n" +
                "其余" + similaritySameNum + "篇相似率相同，占比" + Math.round((float) similaritySameNum * 100/ totalNum) + '%';
        System.out.println(result);
    }

    private Map<String,Integer> readExcelToMap(String path, int indexOfSimilarity) throws IOException {
        HSSFWorkbook excel = new HSSFWorkbook(new FileInputStream(new File(path)));
        HSSFSheet sheet = excel.getSheet("sheet1");
        int idx = 1;
        Map<String,Integer> map = new HashMap<>();
        while (idx < Integer.MAX_VALUE) {
            try{
                HSSFRow row = sheet.getRow(idx);
                String taskid = row.getCell(0).toString();
                String similarity = row.getCell(indexOfSimilarity).toString();
                if(similarity.startsWith("1")){
                    similarity = ".100";
                } else if (similarity.endsWith("00")){
                    similarity = ".0";
                }
                similarity = similarity.substring(1);
                map.put(taskid, Integer.valueOf(similarity));
                idx ++;
            } catch (Exception e){
//                System.out.println("id " + idx + " path" + path + e.getMessage());
                break;
            }
        }
        excel.close();
        return map;
    }

    private int readTimeFromLog(String path, String field) throws IOException {
        BufferedReader html = new BufferedReader(new FileReader(path));
        String line;
        while((line = html.readLine()) != null) {
            if(line.contains(field)){
                return Integer.valueOf(line.split("：")[1]);
            }
        }
        return -1;
    }

    public static void main(String[] args) throws IOException {

        int rowNum = 0;

        HSSFWorkbook sheets = new HSSFWorkbook();
        HSSFSheet sheet1 = sheets.createSheet("sheet1");

        HSSFRow row = sheet1.createRow(rowNum++);
        int a = 0;
        row.createCell(a++).setCellValue("文章编号");
        row.createCell(a++).setCellValue("文章字数");
        row.createCell(a++).setCellValue("top25");
        row.createCell(a++).setCellValue("top20");
//        row.createCell(a++).setCellValue("kk-400w");
//        row.createCell(a++).setCellValue("kk-200w");


        String free0 = FileUtils.readFileToString(new File("C:\\Users\\YouAreJ\\Downloads\\top25.txt"),StandardCharsets.UTF_8);
        free0 = kkk(free0);
        String free1 = FileUtils.readFileToString(new File("C:\\Users\\YouAreJ\\Downloads\\top20.txt"),StandardCharsets.UTF_8);
        free1 = kkk(free1);
//        String free2 = FileUtils.readFileToString(new File("C:\\Users\\YouAreJ\\Downloads\\kk-500w.txt"),StandardCharsets.UTF_8);
//        free2 = kkk(free2);
//        String free3 = FileUtils.readFileToString(new File("C:\\Users\\YouAreJ\\Downloads\\kk-400w.txt"),StandardCharsets.UTF_8);
//        free3 = kkk(free3);
//        String free4 = FileUtils.readFileToString(new File("C:\\Users\\YouAreJ\\Downloads\\kk-200w.txt"),StandardCharsets.UTF_8);
//        free4 = kkk(free4);
        List<Double> free00 = Arrays.stream(free0.trim().split("\\s+")).map(v->Double.parseDouble(v)*100).collect(Collectors.toList());
        List<Double> free11 = Arrays.stream(free1.trim().split("\\s+")).map(v->Double.parseDouble(v)*100).collect(Collectors.toList());
//        List<Double> free22 = Arrays.stream(free2.trim().split("\\s+")).map(v->Double.parseDouble(v)*100).collect(Collectors.toList());
//        List<Double> free33 = Arrays.stream(free3.trim().split("\\s+")).map(v->Double.parseDouble(v)*100).collect(Collectors.toList());
//        List<Double> free44 = Arrays.stream(free4.trim().split("\\s+")).map(v->Double.parseDouble(v)*100).collect(Collectors.toList());

        for(int i = 0; i < 1000; i++){
            try {
                HSSFRow r = sheet1.createRow(rowNum);
                int b = 0;

                r.createCell(b++).setCellValue(rowNum);
                r.createCell(b++).setCellValue(sentenceLengthNew(FileUtils.readFileToString(new File("C:\\Users\\YouAreJ\\Desktop\\es\\testfile\\" + uu(rowNum)), StandardCharsets.UTF_8)));
                r.createCell(b++).setCellValue(parse(free00.get(i),1));
                r.createCell(b++).setCellValue(parse(free11.get(i),1));
//                r.createCell(b++).setCellValue(parse(free22.get(i),1));
//                r.createCell(b++).setCellValue(parse(free33.get(i),1));
//                r.createCell(b++).setCellValue(parse(free44.get(i),1));
            } catch (Exception e) {
                e.printStackTrace();
            }
//            r.createCell(b++).setCellValue(parse(vip00.get(i),1));
//            r.createCell(b++).setCellValue(parse(vip11.get(i),1));
//            r.createCell(b++).setCellValue(parse(svip00.get(i),1));
//            r.createCell(b++).setCellValue(parse(svip11.get(i),1));

            rowNum++;
        }

        sheets.write(new File("result.xls"));











//        HSSFWorkbook excel = new HSSFWorkbook(new FileInputStream(new File("E:\\Desktop\\origin200614083625.xls")));
//        HSSFSheet sheet = excel.getSheet("sheet1");
//        int idx = 1;
//        Map<String,Integer> map = new HashMap<>();
//        while (idx < Integer.MAX_VALUE) {
//            try{
//                HSSFRow row = sheet.getRow(idx);
//                String taskid = row.getCell(0).toString();
//                String similarity = row.getCell(4).toString();
//                if(similarity.startsWith("1")){
//                    similarity = ".100";
//                } else if (similarity.endsWith("00")){
//                    similarity = ".0";
//                }
//                similarity = similarity.substring(1);
//                if(map.containsKey(taskid)){
//                    System.out.println();
//                }
//                map.put(taskid, Integer.valueOf(similarity));
//                idx ++;
//            } catch (Exception e){
////                System.out.println("id " + idx + " path" + path + e.getMessage());
//                break;
//            }
//        }
//        excel.close();
    }

    public static void maicn(String[] args) throws IOException {

        int rowNum = 0;

        HSSFWorkbook sheets = new HSSFWorkbook();
        HSSFSheet sheet1 = sheets.createSheet("sheet1");

        HSSFRow row = sheet1.createRow(rowNum++);
        row.createCell(0).setCellValue("关键词数量");
        row.createCell(1).setCellValue("ES查询总次数");
        row.createCell(2).setCellValue("ES返回结果总数");
        row.createCell(3).setCellValue("cos通过总数");
        row.createCell(4).setCellValue("ES查询总耗时");

        for(int i = 0; i <= 310; i++){
            try {
                String key0 = i + ".search";
                String key1 = i + ".hits";
                String key2 = i + ".pass";
                String key3 = i + ".time";
                long search = parse0(RedisUtil.get(key0));
                long hits = parse0(RedisUtil.get(key1));
                long pass = parse0(RedisUtil.get(key2));
                long time = parse0(RedisUtil.get(key3));
                HSSFRow r = sheet1.createRow(rowNum);

                r.createCell(0).setCellValue(i);
                r.createCell(1).setCellValue(search);
                r.createCell(2).setCellValue(hits);
                r.createCell(3).setCellValue(pass);
                r.createCell(4).setCellValue(time);

                rowNum++;
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        sheets.write(new File("result.xls"));
    }
    public static Long parse0(String value){
        try {
            return Long.parseLong(value);
        } catch (Exception e){
            return (long)0;
        }
    }

    public static String kkk(String ss){
        String[] split = ss.trim().split("\\n+");
        StringBuilder sb = new StringBuilder();
        boolean start = false;
        for(String a : split){
            if(start && ! CharacterHelper.containsHanScript(a)){
                sb.append(a);
            } else if(a.startsWith("bTime - aTime")){
                start = true;
            }
        }
        return sb.toString();
    }

    public static float parse(double decimal, int scale){
        if(decimal == 0 || Double.isNaN(decimal) || decimal == Float.NEGATIVE_INFINITY || decimal == Float.POSITIVE_INFINITY){
            return 0;
        }
        BigDecimal b = new BigDecimal(decimal);
        float similarity = b.setScale(scale, RoundingMode.HALF_UP).floatValue();
        return Math.max(similarity,0.001F);
    }

    // 计算句子长度，一个汉字算一个字，连续的字母或数字算一个字
    public static int sentenceLengthNew(String str){
        int len = 0;
        int lenForEng = 0;
        int chineseCharCount = 0;
        boolean lastWordIsEngOrDigit = false;
        int lengthOfSerialEnglishOrDigit = 0;
        for(char c : str.toCharArray()){
            if(CharacterHelper.isNormalChineseChar(c)){
                len ++;
                lenForEng++;
                chineseCharCount++;
                if(lastWordIsEngOrDigit){
                    len ++;
                    lenForEng += (lengthOfSerialEnglishOrDigit < 5 ? 1 : 2);
                    lastWordIsEngOrDigit = false;
                    lengthOfSerialEnglishOrDigit = 0;
                }
            } else if ((CharacterHelper.isEnglishChar(c) || CharacterHelper.isNumberChar(c)) && lengthOfSerialEnglishOrDigit < 35){
                lastWordIsEngOrDigit = true;
                lengthOfSerialEnglishOrDigit ++;
            } else if (lastWordIsEngOrDigit){
                len ++;
                lenForEng += (lengthOfSerialEnglishOrDigit < 5 ? 1 : 2);
                lastWordIsEngOrDigit = false;
                lengthOfSerialEnglishOrDigit = 0;
            }
        }
        if(lastWordIsEngOrDigit){
            len++;
            lenForEng += (lengthOfSerialEnglishOrDigit < 5 ? 1 : 2);
        }
        return lenForEng;
    }

    private static String uu(int rowNum){
        String name = "0000" + (rowNum - 1) + ".txt";
        return name.substring(name.length() - 8);
    }

}
